﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace MIPS_Simulator
{
    class ProgramCounter
    {
        public int ClockCycles
        {
            set;
            get;
        }
        private short nextInstruction;
        public short NextInstruction
        {
            get { return nextInstruction; }
            set { nextInstruction = value; }
        }

        private InstructionMemory instructionMemory;
        public InstructionMemory InstructionMemory { get { return instructionMemory; } set { instructionMemory = value; } }

        private ALU alu;
        public ALU Alu { get { return alu; } set { alu = value; } }

        private List<string> instruction;
        public List<string> Instruction { get { return instruction; } set { instruction = value; } }
        public ProgramCounter(InstructionMemory mem, ALU a)
        {
            InstructionMemory = mem;
            Alu = a;
            Instruction = new List<string>();
            ClockCycles = 0;
        }


        public void Compile()
        {
            String OpCode = (string)Instruction[0];

            switch (OpCode)
            {
                case "bne":

                    if (alu.Zero == false) NextInstruction = (short.Parse(Instruction[3])); break;
                case "beq":
                    if (alu.Zero == true) NextInstruction = (short.Parse(Instruction[3])); break;
                case "j":
                    NextInstruction = (short.Parse(Instruction[1])); break;
                case "jal":
                    NextInstruction = (short.Parse(Instruction[1])); break;
                case "jr":
                    break;

                default: break;


            }

        }
        public bool Fetch()
        {
            ClockCycles++;
            
            string inst;
            inst = instructionMemory.loadWord(nextInstruction);
            try
            {
                if (inst.Equals("end"))
                {
                    return false;
                }
            }catch(Exception ex){
                return false;
            }
            string[] instr = inst.Split(' ');
            Instruction.InsertRange(0, instr);
            NextInstruction++;
            return true;
        }
    }
}